package cn.ctbu.xiaopeng.studentscoremanage.service;


import cn.ctbu.xiaopeng.studentscoremanage.dao.TeacherRepository;
import cn.ctbu.xiaopeng.studentscoremanage.entity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xiaopeng
 * @version 1.0
 */
@Service
public class TeacherService {
    @Autowired
    private TeacherRepository teacherRepository;

    /**
     * 查询所有学生
     *
     * @return
     */

    public List<Teacher> getAll() {
        return teacherRepository.findAll();
    }

    /**
     * 根据id查询教师
     *
     * @param id
     * @return
     */
    public Teacher findById(Integer id) {
        return teacherRepository.findById(id).orElse(null); //orElse(null) 如果查询不到返回null
    }

    /**
     * 根据姓名模糊查询 (like)
     *
     * @param name
     * @return
     */
    public List<Teacher> findByNameLike(String name) {
        return teacherRepository.findByNameLike(name);
    }

    /**
     * 根据姓名和密码查询
     *
     * @param name
     * @param password
     * @return
     */
    public List<Teacher> findByNameAndPassword(String name, String password) {
        return teacherRepository.findByNameAndPassword(name, password);
    }

    /**
     * 添加教师
     *
     * @param teacher
     */
    public Teacher insert(Teacher teacher) {
        return teacherRepository.save(teacher);
    }


    /**
     * 修改教师信息
     *
     * @param teacher
     */
    public Teacher update(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    /**
     * 删除教师
     *
     * @param id
     */
    public void deleteById(Integer id) {
        teacherRepository.deleteById(id);
    }

    /**
     * 查询具有最大工号的教师集合
     *
     * @return
     */
    public List<Teacher> findMaxTno() {
        List<Teacher> teachers = getAll();
        //定义一个变量，用于存储最大工号
        String maxTnoByYear = "";
        for (Teacher teacher : teachers) {
            //提取教师工号的前四位
            String tnoYear = teacher.getTno().substring(0, 4);
            if (tnoYear.compareTo(maxTnoByYear) > 0) {
                maxTnoByYear = tnoYear;
            }
        }

        //根据最大工号的前四位查询教师集合
        return teacherRepository.findByTnoStartingWith(maxTnoByYear);
    }

    /**
     * 根据姓名模糊查询 (like)
     * @param name
     * @return
     */
    public List<Teacher> findByNameStartWith(String name) {
        return teacherRepository.findByNameStartingWith(name);
    }
}
